package handlers

import (
	"errors"
	"strconv"

	"github.com/yjp211/web"

	"mutu/misc/conf"
	"mutu/misc/typedef"
	"mutu/models"
	"mutu/service"
)

type CommentView struct{}

var (
	CommentHandler = CommentView{}
)

func (p CommentView) AddRelComment(ctx *web.Context) string {
	flag, err := strconv.Atoi(ctx.Params["flag"])
	if err != nil {
		flag = conf.F_Action_Matter
	}
	relid, ok := ctx.Params["relid"]
	if !ok {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}

	content := ctx.Params["content"]

	ses := ctx.Dict["session"].(*models.Session)

	m := &models.Comment{
		Content: content,
		Flag:    flag,
		RelId:   relid,
		UserId:  ses.UserId,
		Nick:    ses.Nick,
		Himg:    ses.Himg,
	}
	err = service.CommentService.AddComment(m)
	return JsonpReturn(ctx, nil, err)
}

func (p CommentView) RemoveRelComment(ctx *web.Context) string {

	commentid, ok := ctx.Params["commentid"]
	if !ok {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}

	ses := ctx.Dict["session"].(*models.Session)

	err := service.CommentService.RemoveComment(ses.UserId, commentid)
	return JsonpReturn(ctx, nil, err)
}

func (p CommentView) GetUserComments(ctx *web.Context) string {
	ses := ctx.Dict["session"].(*models.Session)

	var data typedef.Dict

	arr, err := service.CommentService.GetUserComments(ses.UserId)
	if err == nil {
		data = typedef.Dict{
			"count":    len(arr),
			"comments": arr,
		}
	}
	return JsonpReturn(ctx, data, err)
}

func (p CommentView) GetRelComments(ctx *web.Context) string {
	flag, err := strconv.Atoi(ctx.Params["flag"])
	if err != nil {
		flag = conf.F_Action_Matter
	}
	relid, ok := ctx.Params["relid"]
	if !ok {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}

	var data typedef.Dict

	arr, err := service.CommentService.GetRelComments(flag, relid)
	if err == nil {
		data = typedef.Dict{
			"count":    len(arr),
			"comments": arr,
		}
	}
	return JsonpReturn(ctx, data, err)
}
